<?php

namespace app\admin\controller\separate_accounts;

use addons\qrcode\Qrcode;
use app\admin\model\Store;
use app\admin\model\wanlshop\Shop;
use app\api\model\SeparateSet;
use app\api\model\wanlshop\ShopConfig;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\User;
use fast\Random;
use think\Request;
use think\Session;
use wechat\MiniProgramService;
use wechat\WechatController;

class BusinessListings extends Backend
{
    protected $searchFields = 'id,name';
    /**
     * @var mixed
     */
    private $service_secret;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->model = new Store();
        $this->service_secret = Session::get('admin')['secret'];
        if (empty($this->service_secret))
            $this->service_secret = "Jp)GuX=M^KthZV7^";
        if(!empty(Session::get('admin')['secret'])){
            $this->model
                ->where(['service_secret'=>$this->service_secret]);
        }
    }

    /**
     * 查看
     */
    public function store_list(){
        //设置过滤方法
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = array("total" => $list->total(), "rows" => $list->items());
        return json($result);
    }
    public function add()
    {
        $this->extracted();
        return parent::add();
    }
    public function edit($ids = null)
    {
        $this->extracted();
        return parent::edit($ids);
    }
    public function extracted($ids = null)
    {
        if ($this->request->isAjax()){
            $params = $this->request->param("row/a");
            if ($params['status'] == 1){
                // 如果这个等于1 则是要走商户绑定流程
                $secret = SeparateSet::get(['secret'=>$this->service_secret]);
                $wechat = new WechatController($params['sub_mch_id'],$secret);
                $res = $wechat->addReceiver($params);
                if ($res['result_code'] == "FAIL"){
                    $this->error($res['err_code_des']);
                }
            }
        }
    }
    /**
     * 小程序码
     * @return void
     */
    public function gencode($ids){
        $store = $this->model->where(['id'=>$ids])->find();
        $set = SeparateSet::get(['secret'=>$store->service_secret]);
        $wechat = new MiniProgramService($set);
        $res = $wechat->app_code(['path'=>'pages/pay/index','sub_mch_id'=>$store->sub_mch_id,
            'directory'=>"/path/to/directory/"]);
        if ($res['result_code'] == 'FAIL')
            $this->error($res['result_message']);
        Store::update(['payment_code'=>$res['data']],['sub_mch_id'=>$store->sub_mch_id]);
        $this->success("成功生成收款码");
    }
    public function genmch($ids){
        $store = $this->model->where(['id'=>$ids])->find();
        $this->auth = Auth::instance();
        $password = Random::alnum();
        $mobile = $store->mobile;
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('账号已锁定'));
            }
            //如果已经有账号则直接登录
        } else {
            $ret = $this->auth->register($mobile, $password, '', $mobile, []);
            if ($ret){
                $this->model->where(['id'=>$ids])->update(['password'=>$password]);
            }
        }
        $user = \app\common\model\User::getByMobile($mobile);
        $auth = \app\api\model\wanlshop\Auth::get(['user_id'=>$user->id]);
        if(empty($auth)){
            $arr = [
                'user_id' => $user->id,
                'state' => 0,
                'shopname' => $store->shop_name,
                'name' => $store->name,
                'mobile' => $mobile,
                'avatar' => $store->store_image,
                'verify' => 3,
                'status' => 'normal'
            ];
            \app\api\model\wanlshop\Auth::create($arr);
        }
        $shop = Shop::get(['user_id'=>$user->id]);
        if(empty($shop)) {
            $arr = [
                "user_id" => $user->id,
                'shopname' => $store->shop_name,
                'avatar' => $store->store_image,
                'verify' => 3,
                'status' => 'normal',
                'bio' => '个性签名',
            ];
            Shop::create($arr);
            $shop = Shop::get(['user_id'=>$user->id]);
        }
        $config = ShopConfig::get(['shop_id'=>$shop->id]);
        if(empty($config)) {
            $arr = [
                "shop_id" => $shop->id,
                'freight' => 1,
                'category_style' => 1,
                'service_secret' => $this->service_secret,
                'sub_mch_id' => $store->sub_mch_id
            ];
            ShopConfig::create($arr);
        }
        $this->success("商户创建成功");
    }
}